import { ref } from 'vue'
import { DialogTableProps } from './DialogTable'

export default function useTableSelection(props: DialogTableProps) {
  const selectedData = ref<any[]>([])
  const selectedKeys = ref<string[]>([])
  const handleSelectChange = (record, selected: boolean) => {
    const key: string = (props.tableAttrs!.rowKey as any) || 'key'
    const isRadio = props.tableAttrs!.rowSelection?.type === 'radio'
    if (isRadio) {
      selectedData.value = [record]
      selectedKeys.value = [record[key]]
      return
    }
    if (selected) {
      selectedData.value.push(record)
      selectedKeys.value.push(record[key])
      return
    }
    const index = selectedData.value.findIndex(
      (item) => item[key] === record[key]
    )
    if (index >= 0) {
      selectedData.value.splice(index, 1)
      selectedKeys.value.splice(index, 1)
    }
  }
  const handleSelectAll = (selected, selectedRows, changeRows: any[]) => {
    for (const row of changeRows) {
      handleSelectChange(row, selected)
    }
  }
  return {
    selectedData,
    selectedKeys,
    handleSelectChange,
    handleSelectAll
  }
}
